import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

//登录组件
import Login from '../component/Login/Login.vue'
//Home组件
import Home from '../component/Home/Home.vue'
//用户列表组件
import User from '../component/User/User.vue'
//权限列表组件
import Right from '../component/Right/Right.vue'
import Roles from '../component/Roles/Roles.vue'

//商品分类组件
import Cate from '../component/Goods/Cate/Cate.vue'



const routes = [
  {
    path:"/",
    redirect:'/login'
  },
  {
    path:"/login",
    name:"Login",
    component:Login
  },
  {
    path:"/home",
    name:"Home",
    component:Home,
    children: [
      {
        path:"/",
        redirect:"/welcome"
      },
      {
        path:"/welcome",
        name:"Welcome",
        component: () => import('../component/Welcome.vue')//懒加载Welcome组件
      },
      {
        path:"/users",
        name:"User",
        component: User
      },
      {
        path:"/rights",
        name:"Right",
        component: Right
      },
      {
        path:"/roles",
        name:"Roles",
        component: Roles
      },
      {
        path:"/categories",
        name:"Cate",
        component: Cate
      }
    ]
  }
]


const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

//添加前置路由导航守卫：
router.beforeEach((to, from, next) => {
  //to代表将要去访问的路径
  //from代表从哪里来
  //next代表是否放行，是一个函数，如果不给参数，直接放行至下一个配置的路由页，如果给一个路由参数，则强制跳转回给定的路由页
  if(to.path == '/login') return next()//访问登录页直接放行就好了
  //如果不是登录页，其他页面都是需要权限才能访问的，判断浏览器对象sessionStorage里是否有token值，没有则强制跳回登录页
  const tokenStr = window.sessionStorage.getItem('token')
  if(!tokenStr) return next('/login')//如果没有token值强制跳转回登录页
  next()//如果判断条件都通过，证明是登录状态，放行即可！ 注意，测试的时候记得先删除sessionStorage里的token值，不然怕有人踩坑，哈哈哈！
})




export default router
